/**
* @project admin-go-api
* @name authMiddleware
* @descriptions 鉴权中间件
* @author 寒锋
* @date 2023-12-12 14:30:22
 */

package middleware

import (
	"admin-go-api/common/response"
	"admin-go-api/constants"
	"admin-go-api/pkg/jwt"
	"github.com/gin-gonic/gin"
	"strings"
)

func AuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			response.Failed(c, int(constants.ApiCode.DISALLOW), constants.ApiCode.GetMessage(constants.ApiCode.DISALLOW))
			c.Abort()
			return
		}
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			response.Failed(c, int(constants.ApiCode.AuthFromAtError), constants.ApiCode.GetMessage(constants.ApiCode.AuthFromAtError))
			c.Abort()
			return
		}
		// todo  验证token
		mc, err := jwt.ValidateToken(parts[1])
		if err != nil {
			response.Failed(c, int(constants.ApiCode.InvalidToken), constants.ApiCode.GetMessage(constants.ApiCode.InvalidToken))
			c.Abort()
			return
		}

		// 存储用户信息
		c.Set(constants.ContextKeyUserObj, mc)
		c.Next()
	}
}
